package com.seekting.autosetup;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternGroupFinder {
    public static String findGroupOne(Pattern pattern, String line) {
        Matcher match = pattern.matcher(line);
        if (match.find()) {
            int count = match.groupCount();
            if (count >= 1) {
                return match.group(1);
            }
        }
        return null;

    }

    public static String findOne(Pattern pattern, String line) {
        Matcher match = pattern.matcher(line);
        if (match.find()) {
            return match.group();
        }
        return null;
    }

    public static List<String> find(Pattern pattern, String line) {
        Matcher match = pattern.matcher(line);
        if (match.find()) {
            List<String> result = new ArrayList<>();
            int count = match.groupCount();
            for (int i = 1; i <= count; i++) {
                result.add(match.group(i));
            }

            return result;
        }
        return null;

    }

    public static String replaceAll(Pattern pattern, String line, String replace) {
        Matcher match = pattern.matcher(line);
        StringBuffer stringBuffer = new StringBuffer();
        while (match.find()) {
//            int count = match.groupCount();
//            System.out.println(match.group());
//            for (int i = 1; i <= count; i++) {
//                String group = match.group(i);
//                System.out.println(group);
//            }
            match.appendReplacement(stringBuffer, replace);

        }
        match.appendTail(stringBuffer);
        return stringBuffer.toString();
    }

    public static String replace(Pattern pattern, String line, String[] replace) {
        String replaced = new String(line);
        Matcher match = pattern.matcher(line);
        if (match.find()) {
            int count = match.groupCount();
            for (int i = 1; i <= count; i++) {
                String group = match.group(i);
                replaced.replace(group, replace[i - 1]);
            }

        }
        return replaced;
    }
}
